//==========================================================================================
//
//		OpenNETCF.Samples.SerialCSharp.frmMain
//		Copyright (c) 2003-2009, OpenNETCF Consulting, LLC
//      http://www.opennetcf.com
//
//      Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
//      associated documentation files (the "Software"), to deal in the Software without restriction, 
//      including without limitation the rights to use, copy, modify, merge, publish, distribute, 
//      sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
//      furnished to do so, subject to the following conditions:
//
//      The above copyright notice and this permission notice shall be included in all copies or 
//      substantial portions of the Software.
// 
//      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
//      BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
//      NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
//      DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
//      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
//
//==========================================================================================
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Text;
using OpenNETCF.IO.Serial;

namespace OpenNETCF.Samples.SerialCSharp
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnSettings;
		private System.Windows.Forms.Button btnSend;
		private System.Windows.Forms.TextBox txtRx;
		private System.Windows.Forms.Label Incoming;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		
		public static Port port;
		private DetailedPortSettings portSettings;
		private System.Windows.Forms.Button btnOpenClose;
		private System.Windows.Forms.TextBox txtTx;

		private string displayString = "";
		private frmSettings settingsForm;


		public frmMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// create the port settings
			portSettings = new HandshakeNone();

			// create a default port on COM2 with no handshaking
			port = new Port("COM2:", portSettings);

			// these are fairly inefficient settings
			// for a terminal we want to send/receive all data as it is queued
			// so 1 byte at a time is the best way to go
			port.RThreshold = 1;	// get an event for every 1 byte received
			port.InputLen = 1;		// calling Input will read 1 byte
			port.SThreshold = 1;	// send 1 byte at a time

			// define an event handler
			port.DataReceived +=new Port.CommEvent(port_DataReceived);
			this.Closed+=new EventHandler(frmMain_Closed);
			btnSend.Focus();
		}
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			// close the settings form if it's open
			if(settingsForm != null)
				settingsForm.Dispose();
	
			// release any port resources
			port.Dispose();

			base.Dispose( disposing );
		}
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnSettings = new System.Windows.Forms.Button();
			this.btnSend = new System.Windows.Forms.Button();
			this.txtTx = new System.Windows.Forms.TextBox();
			this.txtRx = new System.Windows.Forms.TextBox();
			this.Incoming = new System.Windows.Forms.Label();
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.btnOpenClose = new System.Windows.Forms.Button();
			// 
			// btnSettings
			// 
			this.btnSettings.Location = new System.Drawing.Point(8, 240);
			this.btnSettings.Size = new System.Drawing.Size(64, 24);
			this.btnSettings.Text = "Settings";
			this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click);
			// 
			// btnSend
			// 
			this.btnSend.Enabled = false;
			this.btnSend.Location = new System.Drawing.Point(168, 240);
			this.btnSend.Size = new System.Drawing.Size(64, 24);
			this.btnSend.Text = "Send";
			this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
			// 
			// txtTx
			// 
			this.txtTx.Location = new System.Drawing.Point(8, 140);
			this.txtTx.Multiline = true;
			this.txtTx.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.txtTx.Size = new System.Drawing.Size(224, 96);
			this.txtTx.Text = "";
			// 
			// txtRx
			// 
			this.txtRx.Location = new System.Drawing.Point(8, 20);
			this.txtRx.Multiline = true;
			this.txtRx.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.txtRx.Size = new System.Drawing.Size(224, 96);
			this.txtRx.Text = "";
			// 
			// Incoming
			// 
			this.Incoming.Location = new System.Drawing.Point(172, 4);
			this.Incoming.Size = new System.Drawing.Size(28, 12);
			this.Incoming.Text = "label1";
			// 
			// label1
			// 
			this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
			this.label1.Location = new System.Drawing.Point(12, 4);
			this.label1.Size = new System.Drawing.Size(68, 16);
			this.label1.Text = "Incoming";
			// 
			// label2
			// 
			this.label2.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
			this.label2.Location = new System.Drawing.Point(12, 124);
			this.label2.Size = new System.Drawing.Size(68, 16);
			this.label2.Text = "Outgoing";
			// 
			// btnOpenClose
			// 
			this.btnOpenClose.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular);
			this.btnOpenClose.Location = new System.Drawing.Point(76, 240);
			this.btnOpenClose.Size = new System.Drawing.Size(64, 24);
			this.btnOpenClose.Text = "Open";
			this.btnOpenClose.Click += new System.EventHandler(this.btnOpenClose_Click);
			// 
			// frmMain
			// 
			this.Controls.Add(this.btnOpenClose);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.txtRx);
			this.Controls.Add(this.txtTx);
			this.Controls.Add(this.btnSend);
			this.Controls.Add(this.btnSettings);
			this.MinimizeBox = false;
			this.Text = "Serial Test";

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>

		static void Main() 
		{
			Application.Run(new frmMain());
		}

		private void btnSettings_Click(object sender, System.EventArgs e)
		{
			if(settingsForm == null)
			{
				settingsForm = new frmSettings();
			}

			settingsForm.Visible = true;
		}

		private void btnOpenClose_Click(object sender, System.EventArgs e)
		{
			if(port.IsOpen)
			{
				if(port.Close())
				{
					btnOpenClose.Text = "Open";
					btnSend.Enabled = false;
				}
			}
			else
			{
				if(port.Open())
				{
					btnOpenClose.Text = "Close";
					btnSend.Enabled = true;
				}
			}
		}

		private void port_DataReceived()
		{
			// since RThreshold = 1, we get an event for every character
			byte[] inputData = new byte[1];

			// read the character
			inputData = port.Input;

			// display as text
			Encoding enc = Encoding.ASCII;
			displayString = enc.GetString(inputData, 0, inputData.Length);
			try 
			{
				this.Invoke(new EventHandler(SetText));
			}
			catch(Exception e) 
			{
				Console.WriteLine(e.Message);
			}
		}

		private void SetText(object o, EventArgs e) 
		{
			txtRx.Text += displayString;
			displayString = string.Empty;
		}


		private void btnSend_Click(object sender, System.EventArgs e)
		{
			byte[] outputData = new byte[1];

			for(int i = 0 ; i < txtTx.Text.Length ; i++)
			{
				outputData[0] = Convert.ToByte(txtTx.Text[i]);
				port.Output = outputData;
			}
		
			// clear the data since we sent it
			txtTx.Text = "";
		}

		private void frmMain_Closed(object sender, EventArgs e)
		{ 
			// close the settings form if it's open
			if(settingsForm != null)
				settingsForm.Dispose();
	
			// release any port resources
			port.Dispose();
		}
	}
}
